use objc2::{declare_class, mutability, ClassType, DeclaredClass};
use objc2_foundation::{NSObject, NSObjectProtocol};
use objc2_ui_kit::{UIApplication, UIApplicationDelegate};

use super::*;

declare_class!(
	pub struct AppDelegate;
	unsafe impl ClassType for AppDelegate {
		type Super = NSObject;
		type Mutability = mutability::MainThreadOnly;
		const NAME: &'static str = "XLoopAppDelegate";
	}
	impl DeclaredClass for AppDelegate {}
	unsafe impl NSObjectProtocol for AppDelegate {}
	unsafe impl UIApplicationDelegate for AppDelegate {
		#[method(applicationDidFinishLaunching:)]
		unsafe fn application_did_finish_launching(&self, application: &UIApplication){ self.did_finish_launching_(application) }
		#[method(applicationWillTerminate:)]
		unsafe fn application_will_terminate(&self, application: &UIApplication){ self.application_will_terminate_(application); }
	}
);

impl AppDelegate {
	fn did_finish_launching_(&self, application: &UIApplication) {
		CACHE.with_borrow(|vars| {
			if let Some(rep) = &vars.gate {
				rep.on_launch(AppRef(application));
			}
		});
	}
	fn application_will_terminate_(&self, application: &UIApplication) {
		CACHE.with_borrow(|vars| {
			if let Some(rep) = &vars.gate {
				rep.on_terminate(AppRef(application));
			}
		});
	}
}
